// pages/order-new-detail/index.js
import { getUserOrderDetail, refund,cancel,orderpay,queryOrder } from '../../api/order'
import { removeObj } from '../../utils/removeObj.js'
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    warmTip:'',
    bindIndex: -1,//点击取消申请的用户下标
    showUserModal:false,//是否显示用户信息模态框
    bindUserModelIndex:0,//点击用户的下标（用于弹出模态框）
    orderid:''
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({orderid:options.orderid})
  },
  re_auth(e){
    wx.navigateTo({
      url: '/pages/qualification_supplement_two/index?applyid='+e.currentTarget.dataset.applyid,
    })
  },
     //主动查询订单支付状态（第四步）
  _queryOrder(orderSn){
    let  that = this
    queryOrder(orderSn).then(res=>{
      if(res.data.msg=="OK"){
       that._getUserOrderDetail(that.data.order.orderId)
      }
  })
},
  //调起官方微信支付接口
  Payment(result,orderSn){
    let that = this
    wx.requestPayment({
      timeStamp: result.timeStamp,
      nonceStr: result.nonceStr,
      package: result.packageValue,
      signType: result.signType,
      paySign:  result.paySign,
      success (res) { 
          //主动查询订单支付状态（第四步）
          that._queryOrder(orderSn)
      },
      fail (res) { 
      }
    })
  },
  //去支付
  toPay(e){
    let that = this 
    //调起官方微信支付接口
      orderpay(that.data.order.orderSn).then(res=>{
        if(res.data.needPay){
          this.Payment(res.data.result,that.data.order.orderSn)
        }else{
            //主动查询订单支付状态（第四步）
            this._queryOrder(that.data.order.orderSn)
        }
      })
    },
  //取消订单
  toCancel(){
    let that = this
    wx.showModal({
      content: '是否删除订单？',
      success (res) {
        if (res.confirm) {
          cancel(that.data.order.orderId).then(res => {
            if(res.code==0){
              wx.showToast({
                title: res.msg,
                icon:'success'
              })
            }else{
              wx.showToast({
                title: res.msg,
                icon:'none'
              })
            }
            setTimeout(function () {
             wx.redirectTo({
               url: '/pages/order/index',
             })
            }, 2000) 
          })
        } else if (res.cancel) {
        }
      }
    })
  },
  _getUserOrderDetail(orderid) {
    getUserOrderDetail(orderid).then(res => {
      let obj = res.data;
      let { actualPrice, totalPrice, integralPrice, couponPrice } = obj.order
      let price = Number(totalPrice) - Number(actualPrice)
      obj.order.price = price > 0 ? price.toFixed(2) : price
      obj.order.totalPrice = totalPrice.toFixed(2)
      obj.order.actualPrice = (actualPrice.toFixed(2) + '').split('.')
      obj.order.integralPrice = integralPrice > 0 ? integralPrice.toFixed(2) : integralPrice
      obj.order.couponPrice = couponPrice > 0 ? couponPrice.toFixed(2) : couponPrice
      obj.join = removeObj(obj.join, ['searchValue', 'createBy', 'createTime', 'updateBy', 'updateTime','params'])
      this.setData({ ...obj })
    })
  },
  showModel(e) {
    let { index } = e.currentTarget.dataset
    let { join}=this.data
    // console.log(e)
    if (typeof (e.detail) == 'boolean') {
      this.setData({ showUserModal: e.detail })
    } else {
      this.setData({ bindUserModelIndex: index })
      this.setData({ showUserModal: true })
    }
  },
  choosestate(e){
    let {index,state1,state,participantsId} = e.currentTarget.dataset
    if (state1 == 0) {
      this.setData({bindIndex: index})
    }
    if(state!=3&&state!=4){
      if(state1==0){
        this.refundOrderUser(participantsId)
      }
    }
  },
  getTextarea(e) {
    this.setData({ textareaValue: e.detail.value.replace(/(^\s*)|(\s*$)/g, "") })
  },
  toRefund() {
    this.setData({ showRefund: !this.data.showRefund })
  },
  //重新报名
  anew() {
    // console.log(this.data.order.matchId)
    wx.navigateTo({
      url: '/pages/competition_detail/index?id=' + this.data.order.matchId,
    })
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this._getUserOrderDetail(this.data.orderid)
  },
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this._getUserOrderDetail(this.data.order.orderId)
  },
  refundOrder(){
    let {orderId,skuType}=this.data.order
    if(skuType==1){
      wx.navigateTo({
        url: '/pages/order-refund/index?all=1&orderid='+orderId,
      })
    }else{
      wx.navigateTo({
        url: '/pages/order-refund/index?all=1&orderid='+orderId,
      })
      // let obj={
      //   orderId:orderId,
      //   refundRemark:''//退款说明
      // }
      // refund(obj).then(res=>{
      //   wx.showModal({
      //     title: '',
      //     content: '申请中',
      //     showCancel: false,//是否显示取消按钮
      //     confirmText: "确定",//默认是“确定”
      //     confirmColor: '#000000',//确定文字的颜色
      //     success: function (res) {
      //       wx.startPullDownRefresh()
      //     }
      //   })
      // })
    }
  },
  refundOrderUser(participantsId){
    wx.navigateTo({
      url: '/pages/order-refund/index?participantsId='+participantsId,
    })
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  onUnload: function () {
    //如果是订单列表进来，正常返回，如果是下单流程进入订单详情，则返回到详情页面
    var pages = getCurrentPages();//页面指针数组
    var prepage = pages[pages.length - 2];//上一页面指针
    console.log(prepage.route)
    if (prepage.route == "pages/order/index") {

    }else if (prepage.route == "pages/competition_detail/index"){
     
    } else {
      wx.navigateBack({
        delta: 2
      })
    }
  }
})